import {
  pieTemplateFactory,
  barTemplateFactory,
  _ts,
  tendencyTemplateFactory,
  tendencyXAxisFactory,
  tendencyYAxisFactory,
  tendencyBarSeriesFactory,
  tendencyLineSeriesFactory,
  COLOR_LIST
} from "./utils"
import { messages } from "share/common";

function toPercentage(num) {
  return ((num || 0) * 100).toFixed(2) + '%';
}

/**
 * 这个文件用来生成echarts的options
 */

/**
 * 通用饼图
 * @param data
 * @param verticalLegend
 * @param subtext 副标题
 * @returns {{tooltip, legend, series}}
 */
export function commonPieReportFactory(data, verticalLegend, subtext) {
  let template = pieTemplateFactory(verticalLegend);
  let legendData = [], seriesData = [];
  let total = 0;
  data.forEach(item => {
    let { label: name, value, criteria } = item;
    item._valueNum = (Number(value) || 0);
    total += item._valueNum;
    legendData.push(name);
    seriesData.push({
      value,
      name,
      criteria
    });
  });
  seriesData.forEach(item => {
    item._percentageStr = toPercentage((Number(item.value) || 0) / total);
  });
  if (subtext) {
    template.title = {
      text: total,
      textAlign: 'center',
      subtext,
      bottom: 'center',
      left: '59%'
    }
  }
  template.legend.data = legendData;
  template.series[0].data = seriesData;
  return template;
}

/**
 * 通用柱状图
 * @param data
 * @param colorIndex
 * @param criteriaKey 用于赋值criteria，criteria是图表点击时用于搜索的值
 * @returns {{tooltip, legend, series}}
 */
export function commonBarReportFactory(data, colorIndex, criteriaKey, showLegend) {
  let template = barTemplateFactory(colorIndex, showLegend);
  let yAxisData = [], seriesData = [];
  let total = 0;
  data.map(item => {
    let { value, label } = item;
    item._valueNum = (Number(value) || 0);
    total += item._valueNum;
    if (criteriaKey) {
      item.criteria = item[criteriaKey];
    }
    yAxisData.push(_ts(label));
    seriesData.push(item);
  });

  seriesData.forEach(item => {
    item._percentageStr = toPercentage(item._valueNum / total);
  });

  template.yAxis[0].data = yAxisData;
  template.series[0].data = seriesData;
  /*
  * 提示框不截取字符串，由于字符串太长，不仅需要把字符串格式化，
  * 还需要对字符串显示的位置进行处理，不然显示在图标区外面，也会看不见
  * */

  /**
   * 所有label在hover时都展示全部，为避免过长被遮挡，全部重写position
   *
   * 提示框不截取字符串，由于字符串太长，不仅需要把字符串格式化，
   * 还需要对字符串显示的位置进行处理，不然显示在图标区外面，也会看不见
   * @param point
   * @param params
   * @param dom
   * @param rect
   * @param size
   */
  template.tooltip.position = function (point, params, dom, rect, size) {
    // 鼠标坐标和提示框位置的参考坐标系是：以外层div的左上角那一点为原点，x轴向右，y轴向下
    // 提示框位置
    let x = 0, y = 0; // x坐标位置,y坐标位置
    // 当前鼠标位置
    let pointX = point[0], pointY = point[1];
    // 外层div大小
    // var viewWidth = size.viewSize[0];
    // var viewHeight = size.viewSize[1];
    // 提示框大小
    let boxWidth = size.contentSize[0], boxHeight = size.contentSize[1];
    // boxWidth > pointX 说明鼠标左边放不下提示框
    if (boxWidth > pointX) {
      x = 5;
    } else { // 左边放的下
      x = pointX - boxWidth;
    }
    // boxHeight > pointY 说明鼠标上边放不下提示框
    if (boxHeight > pointY) {
      y = 5;
    } else { // 上边放得下
      y = pointY - boxHeight;
    }
    return [x, y];
  };

  return template;
}

/**
 * 通用多系列柱状图(目前多系列的，只有两个系列)
 * @param data
 * @param legendData 当有多个系列时，显示的系列标签
 * @param extraData
 *        colorArr  颜色数组，用于指定每个系列的颜色
 *        criteriaKey 用于赋值criteria，criteria是图表点击时用于搜索的值
 *        hidePercent 不显示百分比（都写好了居然不要百分比，哼）
 *        extraFormatter tooptip上想要显示的额外的信息
 * @returns {{tooltip, legend, series}}
 */
export function commonBarSeriesReportFactory(data, legendData = [], extraData) {
  const { colorArr = [COLOR_LIST[0], COLOR_LIST[1]] } = extraData
  const { criteriaKey = '' } = extraData
  const { hidePercent = false } = extraData
  const { extraFormatter = '' } = extraData
  let template = tendencyTemplateFactory(extraFormatter, hidePercent, true);
  let seriesNumber = legendData.length
  let yAxisData = []
  let seriesData = []

  data.map(item => {
    let { label } = item;
    yAxisData.push(_ts(label));
  })

  if (data.length > 0) {
    for (let i = 0; i < seriesNumber; i++ ) {
      let total = 0;
      let newData = []

      data.map(item => {
        let newItem = { ...item };
        newItem.value = newItem[`value${i + 1}`] || 0;
        newItem._valueNum = (Number(newItem[`value${i + 1}`]) || 0);
        total += newItem._valueNum;
        if (criteriaKey) {
          newItem.criteria = newItem[criteriaKey];
        }
        newData.push(newItem)
      });
      newData.forEach(item => {
        item._percentageStr = toPercentage(item._valueNum / total);
      });
      seriesData.push(newData)
    }
  }

  let seriesExtraParams = {
    barWidth: 8,
    position: 'right'
  }
  seriesData.forEach((seriesItem, index) => {
    let BarSeries = tendencyBarSeriesFactory(legendData[index], seriesItem, colorArr[index], seriesExtraParams);
    template.series.push(BarSeries);
  })

  template.yAxis.push(tendencyXAxisFactory(yAxisData));
  template.xAxis.push(tendencyYAxisFactory('', '{value}', false, true));
  template.legend.data = legendData

  template.xAxis[0].axisLabel.rotate = 30
  template.grid = {
    left: '3%',
    right: '8%',
    top: '8%',
    bottom: '8%',
    containLabel: true
  }


  /*
  * 提示框不截取字符串，由于字符串太长，不仅需要把字符串格式化，
  * 还需要对字符串显示的位置进行处理，不然显示在图标区外面，也会看不见
  * */

  /**
   * 所有label在hover时都展示全部，为避免过长被遮挡，全部重写position
   *
   * 提示框不截取字符串，由于字符串太长，不仅需要把字符串格式化，
   * 还需要对字符串显示的位置进行处理，不然显示在图标区外面，也会看不见
   * @param point
   * @param params
   * @param dom
   * @param rect
   * @param size
   */
  template.tooltip.position = function (point, params, dom, rect, size) {
    // 鼠标坐标和提示框位置的参考坐标系是：以外层div的左上角那一点为原点，x轴向右，y轴向下
    // 提示框位置
    let x = 0, y = 0; // x坐标位置,y坐标位置
    // 当前鼠标位置
    let pointX = point[0], pointY = point[1];
    // 外层div大小
    // var viewWidth = size.viewSize[0];
    // var viewHeight = size.viewSize[1];
    // 提示框大小
    let boxWidth = size.contentSize[0], boxHeight = size.contentSize[1];
    // boxWidth > pointX 说明鼠标左边放不下提示框
    if (boxWidth > pointX) {
      x = 5;
    } else { // 左边放的下
      x = pointX - boxWidth;
    }
    // boxHeight > pointY 说明鼠标上边放不下提示框
    if (boxHeight > pointY) {
      y = 5;
    } else { // 上边放得下
      y = pointY - boxHeight;
    }
    return [x, y];
  };

  return template;
}

/**
 * 成本中心报表
 * @param data
 * @param colorIndex
 * @returns {*}
 */
export function costCenterReportFactory(data, colorIndex) {
  return data.map(item => {
    return {
      name: item.name,
      dataLength: item.costCenterExpenseEntity.length,
      costCenterExpenseEntity: entityFactory(item.name, item.costCenterExpenseEntity)
    }
  });

  /**
   * 处理每一个成本中心
   * @param name
   * @param data
   * @returns {{tooltip, axisLabel, grid, yAxis, xAxis, series}}
   */
  function entityFactory(name, data) {
    let template = commonBarReportFactory(data, colorIndex, undefined, true);
    template.title = {
      _text: name
    };
    template.series[0].name = messages('finance-7.key310')/*金额(元)*/;
    template.legend.data = [messages('finance-7.key310')/*金额(元)*/];
    return template;
  }
}

/**
 * 费用分析图表趋势表
 * @param data
 * @param showYoy 是否显示同比
 * @returns {{tooltip, legend, xAxis, yAxis, series, color}}
 */
export function feeTendencyReportFactory(data, showYoy) {
  let template = tendencyTemplateFactory();
  let xAxisData = [];
  let baseAmountArr = [];
  let qoqArr = [];  // 环比折线图数据
  let yoyAmountArr = [];  // 同比柱状图数据
  let yoyArr = [];  // 同比折线图数据
  let baseAmountTotal = 0;
  let yoyAmountTotal = 0;

  data.forEach(item => {
    item.criteria = item.month;
    xAxisData.push(item.monthName);

    let baseAmountItem = { ...item };
    baseAmountItem.value = baseAmountItem.baseAmount || 0;
    baseAmountItem._valueNum = Number(baseAmountItem.baseAmount) || 0;
    baseAmountTotal += baseAmountItem._valueNum;
    baseAmountArr.push(baseAmountItem);
    let qoqItem = {...item};
    qoqItem.value = item.qoq || 0;
    qoqItem._tooltipValue = qoqItem.value + '%';
    qoqArr.push(qoqItem);

    if (showYoy) {
      let yoyAmountItem = { ...item };
      yoyAmountItem.value = yoyAmountItem.yoyAmount || 0;
      yoyAmountItem._valueNum = Number(yoyAmountItem.yoyAmount) || 0;
      yoyAmountTotal += yoyAmountItem._valueNum;
      yoyAmountArr.push(yoyAmountItem);
      let yoyItem = {...item};
      yoyItem.value = item.yoy || 0;
      yoyItem._tooltipValue = yoyItem.value + '%';
      yoyArr.push(yoyItem);
    }
  });

  template.xAxis.push(tendencyXAxisFactory(xAxisData));
  template.yAxis.push(tendencyYAxisFactory(messages('common.amount')/*金额*/, '{value} 元', true));
  template.yAxis.push(tendencyYAxisFactory(messages('finance-7.key23')/*比率*/, '{value} %', false));

  baseAmountArr.forEach(item => {
    item._percentageStr = toPercentage(item._valueNum / baseAmountTotal);
  });

  let baseAmountBarSeries = tendencyBarSeriesFactory(messages('finance-7.key7')/*当月金额*/, baseAmountArr, COLOR_LIST[0]);
  let qoqLineSeries = tendencyLineSeriesFactory(messages('finance-7.key10')/*环比*/, qoqArr);

  if (showYoy) {
    template.legend.data = [
      messages('finance-7.key7')/*当月金额*/,
      messages('finance-7.key8')/*同比金额*/,
      messages('finance-7.key9')/*同比*/,
      messages('finance-7.key10')/*环比*/
    ];

    yoyAmountArr.forEach(item => {
      item._percentageStr = toPercentage(item._valueNum / yoyAmountTotal);
    });

    let yoyAmountBarSeries = tendencyBarSeriesFactory(messages('finance-7.key8')/*同比金额*/, yoyAmountArr, COLOR_LIST[1]);
    let yoyLineSeries = tendencyLineSeriesFactory(messages('finance-7.key9')/*同比*/, yoyArr);

    template.series.push(baseAmountBarSeries);
    template.series.push(yoyAmountBarSeries);
    template.series.push(yoyLineSeries);
    template.series.push(qoqLineSeries);

  } else {
    template.legend.data = [
      messages('finance-7.key7')/*当月金额*/,
      messages('finance-7.key10')/*环比*/
    ];

    template.series.push(baseAmountBarSeries);
    template.series.push(qoqLineSeries);
  }

  return template
}

/**
 * 借款分析图表趋势表
 * @param data
 * @returns {{tooltip, legend, xAxis, yAxis, series, color}}
 */
export function loanTendencyReportFactory(data) {
  let template = tendencyTemplateFactory();
  let xAxisData = [];
  let loanTotalAmountArr = [];
  let loanBalanceArr = [];  // 同比柱状图数据
  let loanTotalAmountTotal = 0;

  data.forEach(item => {
    item.criteria = item.month;
    xAxisData.push(item.monthName);

    let loanTotalAmountItem = { ...item };
    loanTotalAmountItem.value = loanTotalAmountItem.loanTotalAmountByMonth || 0;
    loanTotalAmountItem._valueNum = Number(loanTotalAmountItem.loanTotalAmountByMonth) || 0;
    loanTotalAmountTotal += loanTotalAmountItem._valueNum;
    loanTotalAmountArr.push(loanTotalAmountItem);

    let loanBalanceItem = { ...item };
    loanBalanceItem.value = loanBalanceItem.loanBalanceByMonth || 0;
    loanBalanceArr.push(loanBalanceItem);
  });

  template.xAxis.push(tendencyXAxisFactory(xAxisData));
  template.yAxis.push(tendencyYAxisFactory(messages('common.amount')/*金额*/, '{value} 元', true));
  template.yAxis.push(tendencyYAxisFactory(messages('finance-7.key144')/*余额*/, '{value} 元', false));

  loanTotalAmountArr.forEach(item => {
    item._percentageStr = toPercentage(item._valueNum / loanTotalAmountTotal);
  });
  let loanTotalAmountBarSeries = tendencyBarSeriesFactory(messages('finance-7.key145')/*新增借款金额*/, loanTotalAmountArr, COLOR_LIST[0]);

  let loanBalanceBarSeries = tendencyLineSeriesFactory(messages('finance-7.key146')/*借款余额*/, loanBalanceArr);

  template.legend.data = [
    messages('finance-7.key145')/*新增借款金额*/,
    messages('finance-7.key146')/*借款余额*/
  ];
  template.series.push(loanTotalAmountBarSeries);
  template.series.push(loanBalanceBarSeries);

  return template
}

/**
 * 个人费用分析图表趋势表
 * @param data
 * @returns {{tooltip, legend, xAxis, yAxis, series, color}}
 */
export function personnelTendencyReportFactory(data) {
  let template = tendencyTemplateFactory();
  let xAxisData = [];
  let baseAmountArr = [];
  let baseAmountTotal = 0;

  data.forEach(item => {
    item.criteria = item.month;
    xAxisData.push(item.monthName);

    item.value = item.baseAmount || 0;
    item._valueNum = Number(item.baseAmount) || 0;
    baseAmountTotal += item._valueNum;
    baseAmountArr.push(item);
  });

  template.xAxis.push(tendencyXAxisFactory(xAxisData));
  template.yAxis.push(tendencyYAxisFactory(messages('common.amount')/*金额*/, '{value} 元', true));
  baseAmountArr.forEach(item => {
    item._percentageStr = toPercentage(item._valueNum / baseAmountTotal);
  });
  let baseAmountBarSeries = tendencyBarSeriesFactory(messages('finance-7.key7')/*当月金额*/, baseAmountArr, COLOR_LIST[0]);
  template.legend.data = [
    messages('finance-7.key7')/*当月金额*/
  ];
  template.series.push(baseAmountBarSeries);

  return template
}


/**
 * 审批效率分析图表趋势表
 * @param data
 * @returns {{tooltip, legend, xAxis, yAxis, series, color}}
 */
export function approveEfficiencyTendencyReportFactory(data) {
  let template = tendencyTemplateFactory();
  let xAxisData = [];
  let baseCountArr = [];
  let qoqArr = [];  // 环比折线图数据
  let yoyCountArr = [];  // 同比柱状图数据
  let yoyArr = [];  // 同比折线图数据
  let baseCountTotal = 0;
  let yoyCountTotal = 0;

  data.forEach(item => {
    item.criteria = item.month;
    xAxisData.push(item.monthName);

    let baseCountItem = { ...item };
    baseCountItem.value = baseCountItem.baseCount || 0;
    baseCountItem._valueNum = Number(baseCountItem.baseCount) || 0;
    baseCountTotal += baseCountItem._valueNum;
    baseCountArr.push(baseCountItem);
    let qoqItem = {...item};
    qoqItem.value = item.qoq || 0;
    qoqItem._tooltipValue = qoqItem.value + '%';
    qoqArr.push(qoqItem);

    let yoyCountItem = { ...item };
    yoyCountItem.value = yoyCountItem.yoyCount || 0;
    yoyCountItem._valueNum = Number(yoyCountItem.yoyCount) || 0;
    yoyCountTotal += yoyCountItem._valueNum;
    yoyCountArr.push(yoyCountItem);
    let yoyItem = {...item};
    yoyItem.value = item.yoy || 0;
    yoyItem._tooltipValue = yoyItem.value + '%';
    yoyArr.push(yoyItem);
  });

  template.xAxis.push(tendencyXAxisFactory(xAxisData));
  template.yAxis.push(tendencyYAxisFactory(messages('finance-7.key311')/*数量(个)*/, '{value}', true));
  template.yAxis.push(tendencyYAxisFactory(messages('finance-7.key23')/*比率*/, '{value} %', false));

  baseCountArr.forEach(item => {
    item._percentageStr = toPercentage(item._valueNum / baseCountTotal);
  });

  let baseCountBarSeries = tendencyBarSeriesFactory(messages('finance-7.key312')/*当月数量(个)*/, baseCountArr, COLOR_LIST[0]);
  let qoqLineSeries = tendencyLineSeriesFactory(messages('finance-7.key10')/*环比*/, qoqArr);

  template.legend.data = [
    messages('finance-7.key312')/*当月数量(个)*/,
    messages('finance-7.key313')/*上年同期数量(个)*/,
    messages('finance-7.key9')/*同比*/,
    messages('finance-7.key10')/*环比*/
  ];

  yoyCountArr.forEach(item => {
    item._percentageStr = toPercentage(item._valueNum / yoyCountTotal);
  });

  let yoyCountBarSeries = tendencyBarSeriesFactory(messages('finance-7.key313')/*上年同期数量(个)*/, yoyCountArr, COLOR_LIST[1]);
  let yoyLineSeries = tendencyLineSeriesFactory(messages('finance-7.key9')/*同比*/, yoyArr);

  template.series.push(baseCountBarSeries);
  template.series.push(yoyCountBarSeries);
  template.series.push(yoyLineSeries);
  template.series.push(qoqLineSeries);
  return template
}


/**
 * 合同签署日期分析图表趋势表
 * @param data
 * @returns {{tooltip, legend, xAxis, yAxis, series, color}}
 */
export function contractSignDateReportFactory(data) {
  let extraFormatter = data.length > 0 ? `${data[0].year}-` : ''
  let template = tendencyTemplateFactory(extraFormatter, true);
  let xAxisData = [];
  let contractTotalAmountArr = [];  // 合同总额
  let contractTotalCountArr = [];  // 合同数量
  let contractAmountTotal = 0 // 合同总金额

  data.forEach(item => {
    xAxisData.push(item.label);

    let contractAmountItem = { ...item };
    contractAmountItem.value = contractAmountItem.baseAmount || 0;
    contractAmountItem._valueNum = Number(contractAmountItem.baseAmount) || 0;
    contractAmountTotal += contractAmountItem._valueNum;
    contractTotalAmountArr.push(contractAmountItem);

    let contractCountItem = { ...item };
    contractCountItem.value = contractCountItem.baseCount || 0;
    contractTotalCountArr.push(contractCountItem);
  });

  contractTotalAmountArr.forEach(item => {
    item._percentageStr = toPercentage(item._valueNum / contractAmountTotal);
  });

  template.xAxis.push(tendencyXAxisFactory(xAxisData));
  template.yAxis.push(tendencyYAxisFactory(messages('finance-7.key149')/*万元*/, '{value}', false));
  template.yAxis.push(tendencyYAxisFactory(messages('finance-7.key150')/*合同数量(个)*/, '{value}', true));

  template.yAxis[0].nameTextStyle =  {
    align: "left"
  }

  let loanTotalAmountBarSeries = tendencyBarSeriesFactory(messages('finance-7.key151')/*合同总额*/, contractTotalAmountArr, COLOR_LIST[0]);
  let loanBalanceBarSeries = tendencyLineSeriesFactory(messages('finance-7.key152')/*合同数量*/, contractTotalCountArr, COLOR_LIST[3]);

  template.legend.data = [
    messages('finance-7.key151')/*合同总额*/,
    messages('finance-7.key152')/*合同数量*/
  ];
  template.series.push(loanTotalAmountBarSeries);
  template.series.push(loanBalanceBarSeries);

  return template
}
